<?php


namespace App\Repository;


use App\User;
use EasyWeChat\Kernel\Messages\Raw;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\TextCard;
use EasyWeChat\Work\GroupRobot\Messages\Markdown;
use Illuminate\Support\Facades\Log;

class WechatUserRepository
{
    protected $app;
    public function __construct()
    {
        $this->app= \EasyWeChat::work();
    }

    public function send(User $user,$message){
      /*  if (config('app.env')=='local'){
            Log::channel('wechatLead')->info('推送成功:'.$user->realname,$message->toXmlArray());
            return true;
        }*/
        // 准备消息
        $userId=$user->wechatUser->userid ?? '' ;

        if (!$userId){
            Log::channel('wechatLead')->error('推送失败:此用户没有绑定企业微信',$user->toArray());
            return false;
        }
        try {
           $result= $this->app->messenger->message($message)->toUser($userId)->send();
           if (isset($result['errcode'])&&$result['errcode']===0){
               Log::channel('wechatLead')->info('推送成功:'.$user->realname,$message->toXmlArray());
           }
        }catch (\Exception $exception){
            Log::channel('wechatLead')->error('推送失败:$exception->getMessage()',$user->toArray());
        }

    }
}
